<template>
	<view>
		<u-loading-page :loading="is_loading"></u-loading-page>
		<u-navbar :title="info.title" :placeholder="true">
			 <view class="u-nav-slot" slot="left" style="display:flex;align-items:center;justify-content:space-around;padding:3px 8px 3px 7px;opacity:.8;flex-direction:row;border:0.5px #c8c9cc solid;border-radius:200rpx;">
                <u-icon name="arrow-left" size="19" @click="$returnPage()"></u-icon>
                <u-line direction="column" :hairline="false" length="16" margin="0 8px" ></u-line>
                <u-icon name="home" size="20" @click="$returnPage(true)"></u-icon>
            </view>
		</u-navbar>
		<view class="content" style="padding: 30rpx;box-sizing: border-box;" v-if="info.title">
			<view style="font-size: 18px;font-weight: bolder;margin-bottom: 15rpx;">
				{{ info.title || '上报说明' }}
			</view>
			<view>
				<u-parse 
				  :content="info.treeDesc" 
				  @linktap="handleLinkTap"
				  selectable=true
				/>
        <!-- <rich-text :nodes="info.treeDesc"  @itemclick="handleItemClick"></rich-text> -->
<!--        <u-parse :content="info.content"></u-parse>-->
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				identification: null,
				info: {
					title: '加载中...'
				},
				is_loading: true,
				userInfo: []
			};
		},
		// onShareAppMessage(res) {
		// 	if (res.from === 'button') {
		// 	  console.log(res.target)
		// 	}
		// 	return {
		// 	  title: '渝快同城-'+this.info.title,
		// 	  path: 'pages/other/other-nformation?identification='+this.identification,
		// 	  imageUrl: this.$baseUrl + "/share_logos.png"
		// 	}
		// },
		// onShareTimeline(res) {
		// 	if (res.from === 'button') {
		// 	  console.log(res.target)
		// 	}
		// 	return {
		// 	  title: '渝快同城-'+this.info.title,
		// 	  imageUrl: this.$baseUrl + "/share_logos.png"
		// 	}
		// },
		async onLoad(e) {
			this.userInfo = uni.getStorageSync('userInfo')
			this.identification = e.identification
			await this.get_info()
		},
		mounted() {
		},
		methods: {
			handleLinkTap(e) {
				console.log('点击链接:', e);
				
				// 获取链接地址
				const href = e.href || (e.detail && e.detail.href);
				
				if (href) {
					// 检查是否是复制链接（以 copy: 开头）
					if (href.startsWith('copy:')) {
						const textToCopy = href.substring(5); // 移除 'copy:' 前缀
						this.copyText(textToCopy);
					} else if (href.startsWith('tel:')) {
						// 电话号码处理
						const phoneNumber = href.substring(4);
						uni.makePhoneCall({
							phoneNumber: phoneNumber
						});
					} else if (href.startsWith('http')) {
						// 普通网页链接，在浏览器中打开
						uni.navigateTo({
							url: `/pages/webview/webview?url=${encodeURIComponent(href)}`
						});
					} else {
						// 其他链接处理
						// 检查是否是微信ID之类的需要复制的内容
						if (href.includes('jiuhu2021') || href.includes('wechat') || href.includes('wx')) {
							this.copyText(href);
						} else {
							// 默认处理方式
							uni.navigateTo({
								url: href
							});
						}
					}
				} else {
					// 兼容旧的数据格式
					const copyData = e.dataCopy || e['data-copy'] || (e.detail && (e.detail.dataCopy));
					
					if (copyData) {
						if (copyData.startsWith('tel:')) {
							const phoneNumber = copyData.substring(4);
							uni.makePhoneCall({
								phoneNumber: phoneNumber
							});
						} else {
							this.copyText(copyData);
						}
					} else {
						// 尝试从富文本内容中提取数据
						const extractionMethods = [
							() => e['data-copy'],                  
							() => e.dataCopy,                      
							() => e.detail?.copy,                  
							() => e.detail?.dataset?.copy,         
							() => {
								const html = e.detail?.html || '';
								const match = html.match(/data-copy=["']([^"']+)/);
								return match?.[1];
							}
						];
					
						let text;
						for (const method of extractionMethods) {
							text = method();
							if (text) break;
						}
					
						if (text) {
							this.copyText(text);
						} else {
							console.error('无法处理的链接点击事件，事件对象:', e);
						}
					}
				}
			},
			  
			copyText(text) {
				uni.setClipboardData({
					data: text,
					success: () => {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						});
					}
				});
			},
			textFormat(val) {
				if (val) {
					let newString = val.replace(/\n/g, '_@').replace(/\r/g, '_#');
					newString = newString.replace(/_#_@/g, '<br/>'); // IE7-8
					newString = newString.replace(/_@/g, '<br/>'); // IE9、FF、chrome
					newString = newString.replace(/\s/g, '&nbsp;'); // 空格处理
					return newString;
				}
			},
      // 在获取到富文本内容后进行处理
      formatRichText(html) {
        // 移除所有img标签的width属性
		// 先解码
		  let processed = html
		  
		  // 确保 span 标签不被转义
		    // 解码所有被转义的 HTML 标签（包括属性中的>符号）
		    processed = processed.replace(/&lt;(\/?)([a-zA-Z][a-zA-Z0-9-]*)([^&]*)&gt;/g, '<$1$2$3>');
		    
		    // 处理自闭合标签（如 <img />）
		    processed = processed.replace(/&lt;([a-zA-Z][a-zA-Z0-9-]*)([^&]*)\/&gt;/g, '<$1$2/>');
		    
			processed = processed.replace(/<img[^>]*width="[^"]*"/gi, match => {
			  return match.replace(/width="[^"]*"/gi, '')
			})

			// 移除所有img标签的内联width样式
			processed = processed.replace(/<img[^>]*style="[^"]*"/gi, match => {
			  return match.replace(/width:\s*[^;]+;/gi, '')
			})

			// 给所有img标签添加统一的class
			processed = processed.replace(/<img/gi, '<img class="rich-img"')

			return processed
		
      },
      unescapeFunc(content) {
        if (!content) return '';
        try {
          const decoded = uni.base64ToArrayBuffer(content);
          const bytes = new Uint8Array(decoded);
          let str = '';
          let i = 0;
          while (i < bytes.length) {
            const byte1 = bytes[i++];
            if (byte1 < 0x80) {
              // 单字节（ASCII）
              str += String.fromCharCode(byte1);
            } else if (byte1 >= 0xC0 && byte1 < 0xE0) {
              // 双字节（如部分符号）
              const byte2 = bytes[i++];
              str += String.fromCharCode(((byte1 & 0x1F) << 6) | (byte2 & 0x3F));
            } else if (byte1 >= 0xE0 && byte1 < 0xF0) {
              // 三字节（如中文）
              const byte2 = bytes[i++];
              const byte3 = bytes[i++];
              str += String.fromCharCode(
                  ((byte1 & 0x0F) << 12) |
                  ((byte2 & 0x3F) << 6) |
                  (byte3 & 0x3F)
              );
            }
          }
          return str;
        } catch (e) {
          console.error("解码失败:", e);
          return content;
        }
      },
			get_info() {
				return new Promise((suc, err) => {
					this.$http.to_http('system/remark/getRemark', {}, 'GET', false).then(res => {
						res = res.data
						if (res.code != 200) {
							return uni.showToast({
								title: res.msg,
								icon: "none"
							})
						}
            res.data.title ='上报说明'
			 // 先解码和格式化
			  let htmlContent = this.unescapeFunc(res.data.treeDesc)
			  htmlContent = this.formatRichText(htmlContent)
			  

            res.data.treeDesc = this.formatRichText(this.unescapeFunc(res.data.treeDesc))
			// 修改这里：先解码，再格式化，最后转换为 nodes 数组
			console.log(res.data.treeDesc)
            this.info = res.data
						this.is_loading = false
						suc(true);
					}).catch(async err=>{
						// if(err.statusCode = 401){
						// 	await this.get_info()
						// 	suc(true);
						// }
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.u-transition {
		z-index: 9999;
	}
	.copyable-text {
	  color: #007AFF;
	  text-decoration: underline;
	}
</style>
